import Qs from 'qs';
import {
  Message,
  Loading
} from 'element-ui';

let loading //定义loading变量
function startLoading() { //使用Element loading-start 方法
  loading = Loading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.7)',
    target: document.querySelector('.loadingMain')
  })
}

function endLoading() { //使用Element loading-close 方法
  loading.close()
}
//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

export default function (app) {
  let axios = app.$axios;
  // 基本配置
  axios.defaults.timeout = 100000;
  axios.defaults.method = 'post';
  // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  axios.defaults.headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    axios.defaults.transformRequest = [function (data) {
      data = Qs.stringify(data)
      return data
    }],

    // 请求回调
    axios.onRequest(config => {
      showFullScreenLoading()
    })

  // 返回回调
  axios.onResponse(res => {
    const data = res.data;
    tryHideFullScreenLoading()
    switch (data.status) {
      case 'success':
        return res;
      case 'failed':
        if (data.res.indexOf("token") !== -1 || data.res.indexOf("重新登录") !== -1) {
          localStorage.clear();
          sessionStorage.clear();
          app.redirect('/login');
          return res;
        } else if (data.res.indexOf("无权限") !== -1) {
          app.redirect('/403');
          return res;
        }
        return res;
      default:
        return res
    }
  })

  // 错误回调
  axios.onError(error => {
    tryHideFullScreenLoading()
    console.log("错误回调axios.onError:", error)
    // app.redirect('/500');
  })
};